package com.google.code.porntube.snap.analyzer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

import com.google.code.porntube.snap.core.setting.Analyzer;
import com.google.code.porntube.snap.result.Clip;

public final class Rss {
	
	private static Logger log = Logger.getLogger(Rss.class.getName());

	public static LinkedList<Clip> analyze(String catalog) {
		LinkedList<Clip> result = new LinkedList<Clip>();

		Pattern htmlPattern = Pattern.compile("<.+?>", Pattern.DOTALL);
		Pattern tagPattern = Pattern.compile("Tags: .*\n");
		Pattern durationPattern = Pattern.compile("Duration: \\d{2}:\\d{2}");
		URL url;
		BufferedReader reader = null;
		StringBuffer html = new StringBuffer();
		try {
			url = new URL(new StringBuffer(Analyzer.FEED_URL).append(catalog)
					.toString());
			reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;			
			while ((line = reader.readLine()) != null) {
				html.append(line);
				html.append("\r\n");
			}			
		} catch (Exception e) {
			log.log(Level.SEVERE, "FETCH RSS", e);
			return result;
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
			}
		}
		
		try {
			Document document = DocumentHelper.parseText(html.toString());
			List<Node> items = document.selectNodes("/rss/channel/item");
			for(Node item : items) {
				String name = item.selectSingleNode("title").getText().replace("- PornTube.com", "");
				String link = item.selectSingleNode("link").getText();
				String description = item.selectSingleNode("description").getText();
				String pubDate = item.selectSingleNode("pubDate").getText();				
				SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
				Clip clip = new Clip();
				clip.setCatalog(catalog);
				clip.setName(name);
				clip.setUrl(link);
				Date update = sdf.parse(pubDate);
				if(update == null) {
					log.log(Level.WARNING, "PUBDATE CONVERT ERROR", pubDate);
				}
				clip.setUpdate(update);
				Matcher matcher = tagPattern.matcher(description);
				if (matcher.find()) {
					String src = matcher.group(0);
					src = src.replace("Tags: ", "").replace("\n", "")
							.replace(", ", ",");
					matcher = htmlPattern.matcher(src);
					src = matcher.replaceAll("");
					clip.setTag(src);
				}
				matcher = durationPattern.matcher(description);
				if (matcher.find()) {
					String src = matcher.group(0);
					src = src.replace("Duration: ", "");
					clip.setDuration(src);
				}

				com.google.code.porntube.snap.result.Config config = Post.analyze(clip.getUrl());
				clip.setFile(config.getVideo());
				clip.setThumbnail(config.getThumbnail());
				clip.setConfig(config.getUrl());
				result.add(clip);
			}

		} catch (Exception e) {
			log.log(Level.SEVERE, "ANALYZE RSS", e);
		}	
		
		return result;
	}

}
